import { users, verificationCodes } from '../../../server/database/schema';
import {gt} from 'drizzle-orm'

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { email, code } = body;

  const db = useDrizzle()

  // 验证验证码
  const verification = await db.select()
    .from(verificationCodes)
    .where(
      and(
        eq(verificationCodes.email, email),
        eq(verificationCodes.code, code),
        eq(verificationCodes.type, 'login'),
        gt(verificationCodes.expiresAt, new Date())
      )
    )
    .limit(1);

  if (!verification.length || verification[0].used) {
    throw createError({ statusCode: 400, message: 'Invalid verification code' });
  }

  // 获取用户
  const user = await db.select()
    .from(users)
    .where(eq(users.email, email))
    .limit(1);

  if (!user.length) {
    throw createError({ statusCode: 404, message: 'User not found' });
  }

  // 标记验证码已使用
  await db.update(verificationCodes)
    .set({ used: true })
    .where(eq(verificationCodes.id, verification[0].id));

  // 创建会话
  await setUserSession(event, { user: user[0] })

  return { success: true, user: { id: user[0].id, email: user[0].email, nickname: user[0].nickname} };
});